<?php

namespace App\Admin\Models;

use App\Admin\Traits\ModelTree;
use App\Admin\Utils\Admin;
use App\Admin\Models\VueRouter;
use App\Admin\Models\AdminUser;
use Illuminate\Database\Eloquent\Builder;

class VueAdminUserRouter extends Model
{
    use ModelTree {
        ModelTree::allNodesQuery as parentAllNodesQuery;
    }

    protected $casts = [
        'id' => 'integer',
        'parent_id' => 'integer',
        'order' => 'integer',
        'cache' => 'bool',
        'menu' => 'bool',
    ];
    
    protected $fillable = [
        'id',
        'user_id',
        'parent_id',
        'model_id',
        'order',
        'title',
        'icon',
        'path',
        'cache',
        'menu',
        'is_custom',
    ];

    protected $treeWithAuth = false;

    /**
     * parent_id 默认为 0 处理
     *
     * @param $value
     */
    public function setParentIdAttribute($value)
    {
        $this->attributes['parent_id'] = $value ?: 0;
    }

    public function roles()
    {
        return $this->belongsToMany(
            AdminRole::class,
            'vue_router_role',
            'vue_router_id',
            'role_id'
        );
    }

    public function treeWithAuth()
    {
        $this->treeWithAuth = true;
        return $this;
    }

    protected function allNodesQuery(): Builder
    {
        
        return $this->parentAllNodesQuery();
    }

    protected function ignoreTreeNode($node): bool
    {
        return false;
    }

    public function existVueRouter($title){
        return $this->where('title',$title)->first();
    }

    // 创建非管理员用户路由
    public function createVueAdminUserRouter($arr, $userId){
        $user = AdminUser::with(['roles','permissions'])->find($userId);
        $successNums = 0;
        foreach ($arr as $key => $value) {
            if (
                // 角色可见
                (isset($value['roles']) && $user && $user->visible($value['roles']) &&
                // 并且路由没有配置权限，或者配置了权限，用户也有权限
                (empty($value['permission']) || $user->can($value['permission'])))
            ) {
                $value['id'] = $this->getVueAdminUserRouterInsertId($userId, $value['id']);
                $value['user_id'] = $userId;
                $value['is_custom'] = 2;
                $exist = self::where('id',$value['id'])->first();
                if (!$exist) {
                    if ($value['parent_id']!==0) {
                        $value['parent_id'] = $this->getVueAdminUserRouterInsertId($userId, $value['parent_id']);
                    }
                    // 非管理员用户路由配置路径替换
                    if (strstr($value['path'], 'vue-routers')) {
                        $value['path'] = str_replace('vue-routers', 'vue-admin-user-routers', $value['path']);
                    }
                    if (isset($value['permission'])) {
                        unset($value['permission']);
                    }
                    if (self::create($value)) {
                        $successNums++;
                    }
                } else {
                    $successNums++;
                }
                if ($value['children']) {
                    $this->createVueAdminUserRouter($value['children'], $userId);
                }
            }
        }
        return $successNums>0 && count($arr)==$successNums;
    }

    // 获取非管理员用户路由
    public function getVueAdminUserRouterList(){
        $vueAdminUserRouter = new VueAdminUserRouter();
        $routeIdArr = $this->getVueAdminUserRouterId();
        return $vueAdminUserRouter->treeInclude($routeIdArr)->toTree();
    }

    // 获取非管理员用户路由ID
    public function getVueAdminUserRouterId($parent_id=null){
        $vueRouter = new VueRouter();
        if ($parent_id===0 || $parent_id) {
            $routeIdArr = $vueRouter->treeWithAuth()->treeParentId($parent_id)->toRouteId();
        } else {
            $routeIdArr = $vueRouter->treeWithAuth()->toRouteId();
        }
        $appendRouteIdArr = [];
        if ($user = Admin::user()) {
            foreach ($routeIdArr as $key => $value) {
                $routeIdArr[$key] = $this->getVueAdminUserRouterInsertId($user->id, $value);
            }
   
            $this->where('user_id', $user['id'])
                ->where('is_custom', 2)
                ->whereNotIn('id', $routeIdArr)
                ->delete();
            $appendRouteIdArr = $this->where('user_id', $user['id'])
                ->pluck('id')
                ->toArray();
        }
       
        return array_unique(array_merge($routeIdArr, $appendRouteIdArr));
    }

    // 生成非管理员用户路由插入ID
    public function getVueAdminUserRouterInsertId($userId, $routerId=null){
        if ($routerId) {
            return $userId.strrev(sprintf("%013d", $routerId));
        } else {
            return $userId.strrev(getRandomString(13,'0123456789'));
        }
    }
}
